package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        /**互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);
        if(shop == null)
        {
            return Result.fail("查询的店铺不存在！");
        }
         **/
        //逻辑过期解决缓存击穿
       // Shop shop = queryWithLogicalExpire(id);
        //Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,
        //        Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.SECONDS);

        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById,
                CACHE_SHOP_TTL, TimeUnit.SECONDS);
        return Result.ok(shop);
    }

    /**
     * 利用互斥锁解决缓存击穿问题
     * @param id
     * @return
     */
//    public Shop queryWithMutex(Long id)
//    {
//        Shop shop = null;
//
//        String lookKey = LOCK_SHOP_KEY + id;
//        try {
//            String shopJson = null;
//            //3.尝试获取互斥锁
//            while(true)
//            {
//                //1.在redis缓存找
//                shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//                //2. 商品存在
//                if(!StrUtil.isBlank(shopJson))
//                {
//                    //把Json格式的字符串转换成shop对象
//                    shop = JSONUtil.toBean(shopJson,Shop.class);
//                    return shop;
//                }
//                //解决缓存穿透
//                if(shopJson != null)
//                {
//                    return null;
//                }
//                if(lock(lookKey))
//                {
//                    break;
//                }
//                Thread.sleep(50);
//            }
//            //2.双重判定,再次去缓存查找商铺是否存在
//            shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//            if(!StrUtil.isBlank(shopJson)) {
//                //把Json格式的字符串转换成shop对象
//                shop = JSONUtil.toBean(shopJson, Shop.class);
//                return shop;
//            }
//            if(shopJson != null) {
//                return null;
//            }
//
//            //3. 商品不在Redis，从数据库找
//            shop = getById(id);
//            //Thread.sleep(200);
//
//            //4. 商品不在数据库
//            if(shop == null)
//            {
//                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return null;
//            }
//            //5. 商品在数据库中,把商品转换成字符串后添加进缓存
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//            //6.释放互斥锁
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            unLock(lookKey);
//        }
//        return shop;
//    }


//    public void saveShop2Redis(Long id,Long expireSecond)
//    {
//        //1.从数据库查询商铺信息
//        Shop shop = getById(id);
//        try {
//            Thread.sleep(200);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        //2.封装redis数据
//        RedisData redisData = new RedisData();
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
//        //3.将数据写入redis
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
//    }
//
//
//
//
//    //获取互斥锁
//    private boolean lock(String key)
//    {
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(flag);
//    }
//    //释放互斥锁
//    private void unLock(String key)
//    {
//        stringRedisTemplate.delete(key);
//    }


    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null)
        {
            return Result.fail("店铺ID不存在");
        }
        //更新数据库
        updateById(shop);
        //删缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
